package com.csy.user.controller.system;

import com.csy.commons.constant.UserConstants;
import com.csy.commons.core.controller.BaseController;
import com.csy.commons.core.domain.BaseResponse;

import com.csy.commons.core.utils.SecurityUtils;

import com.csy.commons.dto.SysDept;
import com.csy.user.entity.system.service.SysDeptService;
import com.csy.user.utils.TreeSelect;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * 部门控制类
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {

    @Resource
    private SysDeptService deptService;

    /**
     * 查询部门列表
     * @param sysDept
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("@pe.hasPerms('system:dept:list')")
    public BaseResponse<List<SysDept>> findDeptList(SysDept sysDept){
        List<SysDept> sysDepts = deptService.selectDeptList(sysDept);
        return BaseResponse.success(sysDepts);
    }

    /*
    * 根据部门编号获取详细信息
    * */
    @GetMapping(value = "/{deptId}")
    public BaseResponse<SysDept> getInfo(@PathVariable Long deptId){
        return BaseResponse.success(deptService.selectDeptById(deptId));
    }

    /*
    * 新增部门
    * */
    @PostMapping
    public BaseResponse<Integer> add(@RequestBody SysDept sysDept){
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(sysDept))){
            return BaseResponse.fail("新增部门" + sysDept.getDeptName() + "失败，部门名称已经存在");
        }
        sysDept.setCreateBy(SecurityUtils.getUserName());
        return toAjax(deptService.insertDept(sysDept));
    }

    /*
    * 修改部门
    * */
    @PutMapping
    public BaseResponse<Integer> edit(@RequestBody SysDept sysDept){
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(sysDept))){
            return BaseResponse.fail("修改部门" + sysDept.getDeptName() + "失败，部门名称已经存在");
        } else if (sysDept.getParentId().equals(sysDept.getDeptId())) {
            return BaseResponse.fail("修改部门" + sysDept.getDeptName() + "失败，上级部门不能是自己");

        }
        sysDept.setUpdateBy(SecurityUtils.getUserName());
        return toAjax(deptService.updateDept(sysDept));
    }

    /*
    * 删除部门
    * */
    @DeleteMapping("/{deptId}")
    public BaseResponse<Integer> remove(@PathVariable Long deptId){
        if (deptService.hasChildByDeptId(deptId)){
            return BaseResponse.fail("存在下级部门，不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)){

            return BaseResponse.fail("当前部门下存在用户，不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    @GetMapping("/treeselect")
    public BaseResponse<List<TreeSelect>> treeSelect(SysDept sysDept){
        List<SysDept> deptList = deptService.selectDeptList(sysDept);
        List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(deptList);
        return BaseResponse.success(treeSelects);

    }

    /*
    * 查询部门列表 （排除当前节点）
    * */
    @GetMapping("/list/exclude/{deptId}")
    public BaseResponse<List<SysDept>> excludeChild(@PathVariable Long deptId){
        List<SysDept> deptList = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> iterator = deptList.iterator();
        while (iterator.hasNext()){
            SysDept sysDept = (SysDept) iterator.next();
            if (sysDept.getDeptId().intValue() == deptId.intValue()
                || ArrayUtils.contains(StringUtils.split(sysDept.getAncestors(),
                    ","),deptId + "")){

                iterator.remove();
            }
        }

        return BaseResponse.success(deptList);
    }

}
